/*
 * Tencent is pleased to support the open source community by making ovCompose available.
 * Copyright (C) 2025 THL A29 Limited, a Tencent company. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.tencent.compose.sample.mediaquery

import androidx.compose.animation.animateColorAsState
import androidx.compose.animation.core.animateDpAsState
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.huawei.compose.mediaquery.*

/**
 * CMP 媒体查询演示主页面
 * 展示媒体查询系统的各种用例
 */
@Composable
fun MediaQueryDemo(onBackClick: () -> Unit = {}) {
    var selectedTab by remember { mutableStateOf(0) }
    val tabs = listOf(
        "基础查询",
        "设备适配",
        "复杂条件",
        "动态响应",
        "查询信息",
        "单位转换",
        "嵌套条件",
        "实战场景"
    )

    // 提供媒体查询 CompositionLocal
    ProvideMediaQueryLocals {
        Column(modifier = Modifier.fillMaxSize()) {
            // 顶部 AppBar
            TopAppBar(
                title = { Text("媒体查询演示") },
                navigationIcon = {
                    IconButton(onClick = onBackClick) {
                        Icon(Icons.AutoMirrored.Filled.ArrowBack, "返回")
                    }
                },
                backgroundColor = MaterialTheme.colors.primaryVariant,
                contentColor = MaterialTheme.colors.onPrimary
            )

            // Tab 栏
            TabRow(
                selectedTabIndex = selectedTab,
                backgroundColor = MaterialTheme.colors.surface
            ) {
                tabs.forEachIndexed { index, title ->
                    Tab(
                        selected = selectedTab == index,
                        onClick = { selectedTab = index },
                        text = {
                            Text(
                                text = title,
                                fontSize = 14.sp,
                                fontWeight = if (selectedTab == index) FontWeight.Bold else FontWeight.Normal
                            )
                        }
                    )
                }
            }

            // 内容区域
            Box(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(16.dp)
            ) {
                when (selectedTab) {
                    0 -> BasicQueryDemo()
                    1 -> DeviceAdaptationDemo()
                    2 -> ComplexConditionDemo()
                    3 -> DynamicResponseDemo()
                    4 -> QueryInfoDemo()
                    5 -> UnitConversionDemo()
                    6 -> NestedConditionDemo()
                    7 -> PracticalScenarioDemo()
                }
            }
        }
    }
}

/**
 * 示例 1: 基础查询演示
 * 展示 rememberIsLandscape、rememberIsDarkMode、rememberDeviceType 等基础 API
 */
@Composable
private fun BasicQueryDemo() {
    val isLandscape = rememberIsLandscape()
    val isDarkMode = rememberIsDarkMode()
    val deviceType = rememberDeviceType()

    Column(
        modifier = Modifier

            .fillMaxSize()
            .verticalScroll(rememberScrollState())
    ) {
        Text(
            text = "基础媒体查询",
            style = MaterialTheme.typography.h6,
            fontWeight = FontWeight.Bold
        )

        Spacer(modifier = Modifier.height(8.dp))

        Text(
            text = "使用快捷查询函数获取设备状态",
            style = MaterialTheme.typography.body1,
            color = Color.Gray
        )

        Spacer(modifier = Modifier.height(16.dp))

        // 屏幕方向查询
        Card(
            modifier = Modifier.fillMaxWidth(),
            backgroundColor = MaterialTheme.colors.primaryVariant
        ) {
            Column(
                modifier = Modifier.padding(16.dp)
            ) {
                Text(
                    text = "屏幕方向查询",
                    fontSize = 18.sp,
                    fontWeight = FontWeight.Bold,
                    color = MaterialTheme.colors.onPrimary
                )

                Spacer(modifier = Modifier.height(8.dp))

                Text(
                    text = "API: rememberIsLandscape()",
                    fontSize = 12.sp,
                    fontFamily = androidx.compose.ui.text.font.FontFamily.Monospace,
                    color = MaterialTheme.colors.onPrimary.copy(alpha = 0.7f)
                )

                Spacer(modifier = Modifier.height(8.dp))

                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.SpaceBetween,
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Text(
                        text = if (isLandscape.value) "横屏模式" else "竖屏模式",
                        fontSize = 20.sp,
                        fontWeight = FontWeight.Bold,
                        color = MaterialTheme.colors.primary
                    )

                    Surface(
                        shape = RoundedCornerShape(8.dp),
                        color = if (isLandscape.value)
                            MaterialTheme.colors.primary
                        else
                            MaterialTheme.colors.secondary
                    ) {
                        Text(
                            text = if (isLandscape.value) "LANDSCAPE" else "PORTRAIT",
                            modifier = Modifier.padding(horizontal = 12.dp, vertical = 6.dp),
                            color = Color.White,
                            fontWeight = FontWeight.Bold
                        )
                    }
                }
            }
        }

        Spacer(modifier = Modifier.height(16.dp))

        // 深色模式查询
        Card(
            modifier = Modifier.fillMaxWidth(),
            backgroundColor = MaterialTheme.colors.secondary
        ) {
            Column(
                modifier = Modifier.padding(16.dp)
            ) {
                Text(
                    text = "深色模式查询",
                    fontSize = 18.sp,
                    fontWeight = FontWeight.Bold,
                    color = MaterialTheme.colors.onSecondary
                )

                Spacer(modifier = Modifier.height(8.dp))

                Text(
                    text = "API: rememberIsDarkMode()",
                    fontSize = 12.sp,
                    fontFamily = androidx.compose.ui.text.font.FontFamily.Monospace,
                    color = MaterialTheme.colors.onSecondary.copy(alpha = 0.7f)
                )

                Spacer(modifier = Modifier.height(8.dp))

                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.SpaceBetween,
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Text(
                        text = if (isDarkMode.value) "深色模式" else "浅色模式",
                        fontSize = 20.sp,
                        fontWeight = FontWeight.Bold,
                        color = MaterialTheme.colors.primaryVariant
                    )

                    Surface(
                        shape = RoundedCornerShape(8.dp),
                        color = if (isDarkMode.value) Color.DarkGray else Color.LightGray
                    ) {
                        Text(
                            text = if (isDarkMode.value) "DARK" else "LIGHT",
                            modifier = Modifier.padding(horizontal = 12.dp, vertical = 6.dp),
                            color = if (isDarkMode.value) Color.White else Color.Black,
                            fontWeight = FontWeight.Bold
                        )
                    }
                }
            }
        }

        Spacer(modifier = Modifier.height(16.dp))

        // 设备类型查询
        Card(
            modifier = Modifier.fillMaxWidth(),
            backgroundColor =
                MaterialTheme.colors.primaryVariant
        )
        {
            Column(
                modifier = Modifier.padding(16.dp)
            ) {
                Text(
                    text = "设备类型查询",
                    fontSize = 18.sp,
                    fontWeight = FontWeight.Bold,
                    color = MaterialTheme.colors.onPrimary
                )

                Spacer(modifier = Modifier.height(8.dp))

                Text(
                    text = "API: rememberDeviceType()",
                    fontSize = 12.sp,
                    fontFamily = androidx.compose.ui.text.font.FontFamily.Monospace,
                    color = MaterialTheme.colors.onPrimary.copy(alpha = 0.7f)
                )

                Spacer(modifier = Modifier.height(8.dp))

                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.SpaceBetween,
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Text(
                        text = getDeviceTypeDisplayName(deviceType.value),
                        fontSize = 20.sp,
                        fontWeight = FontWeight.Bold,
                        color = MaterialTheme.colors.primary
                    )

                    Surface(
                        shape = RoundedCornerShape(8.dp),
                        color = getDeviceTypeColor(deviceType.value)
                    ) {
                        Text(
                            text = deviceType.value.value.uppercase(),
                            modifier = Modifier.padding(horizontal = 12.dp, vertical = 6.dp),
                            color = Color.White,
                            fontWeight = FontWeight.Bold
                        )
                    }
                }
            }
        }
    }
}

/**
 * 示例 2: 设备适配演示
 * 根据设备类型显示不同的布局
 */
@Composable
private fun DeviceAdaptationDemo() {
    val deviceType = rememberDeviceType()
    val isLandscape = rememberIsLandscape()

    Column(
        modifier = Modifier
            .fillMaxSize()
            .verticalScroll(rememberScrollState())
    ) {
        Text(
            text = "设备自适应布局",
            style = MaterialTheme.typography.h6,
            fontWeight = FontWeight.Bold
        )

        Spacer(modifier = Modifier.height(8.dp))

        Text(
            text = "根据设备类型和屏幕方向自动调整布局",
            style = MaterialTheme.typography.body1,
            color = Color.Gray
        )

        Spacer(modifier = Modifier.height(16.dp))

        // 当前设备信息
        Card(
            modifier = Modifier.fillMaxWidth(),
            backgroundColor =
                MaterialTheme.colors.primaryVariant

        ) {
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(16.dp),
                horizontalArrangement = Arrangement.SpaceBetween
            ) {
                Column {
                    Text(
                        text = "设备类型",
                        fontSize = 12.sp,
                        color = Color.Gray
                    )
                    Text(
                        text = getDeviceTypeDisplayName(deviceType.value),
                        fontSize = 16.sp,
                        fontWeight = FontWeight.Bold,
                        color = MaterialTheme.colors.primary
                    )
                }

                Column(horizontalAlignment = Alignment.End) {
                    Text(
                        text = "屏幕方向",
                        fontSize = 12.sp,
                        color = Color.Gray
                    )
                    Text(
                        text = if (isLandscape.value) "横屏" else "竖屏",
                        fontSize = 16.sp,
                        fontWeight = FontWeight.Bold,
                        color = MaterialTheme.colors.primaryVariant
                    )
                }
            }
        }

        Spacer(modifier = Modifier.height(16.dp))

        // 自适应网格
        val columns = when (deviceType.value) {
            DeviceType.PHONE -> if (isLandscape.value) 3 else 2
            DeviceType.TABLET -> if (isLandscape.value) 5 else 3
            DeviceType.TV -> 6
            DeviceType.WEARABLE -> 1
            else -> 2
        }

        Text(
            text = "自适应网格 (当前列数: $columns)",
            fontSize = 16.sp,
            fontWeight = FontWeight.Bold,
            modifier = Modifier.padding(bottom = 8.dp)
        )

        LazyVerticalGrid(
            columns = GridCells.Fixed(columns),
            contentPadding = PaddingValues(8.dp),
            horizontalArrangement = Arrangement.spacedBy(8.dp),
            verticalArrangement = Arrangement.spacedBy(8.dp),
            modifier = Modifier
                .fillMaxWidth()
                .height(300.dp)
        ) {
            items(12) { index ->
                Card(
                    modifier = Modifier
                        .fillMaxWidth()
                        .aspectRatio(1f),
                    backgroundColor =
                        MaterialTheme.colors.secondary

                ) {
                    Box(
                        contentAlignment = Alignment.Center,
                        modifier = Modifier.fillMaxSize()
                    ) {
                        Text(
                            text = "${index + 1}",
                            fontSize = 20.sp,
                            fontWeight = FontWeight.Bold,
                            color = MaterialTheme.colors.onSecondary
                        )
                    }
                }
            }
        }

        Spacer(modifier = Modifier.height(16.dp))

        // 设备特定布局说明
        Card(
            modifier = Modifier.fillMaxWidth(),
            backgroundColor =
                MaterialTheme.colors.surface

        ) {
            Column(
                modifier = Modifier.padding(16.dp)
            ) {
                Text(
                    text = "设备适配策略",
                    fontSize = 16.sp,
                    fontWeight = FontWeight.Bold
                )

                Spacer(modifier = Modifier.height(8.dp))

                Text(
                    text = "• 手机竖屏: 2列\n" +
                            "• 手机横屏: 3列\n" +
                            "• 平板竖屏: 3列\n" +
                            "• 平板横屏: 5列\n" +
                            "• TV: 6列\n" +
                            "• 穿戴设备: 1列",
                    fontSize = 14.sp,
                    color = Color.Gray,
                    lineHeight = 22.sp
                )
            }
        }
    }
}

/**
 * 示例 3: 复杂条件查询
 * 展示组合条件和逻辑操作符的使用
 */
@Composable
private fun ComplexConditionDemo() {
    Column(
        modifier = Modifier
            .fillMaxSize()
            .verticalScroll(rememberScrollState())
    ) {
        Text(
            text = "复杂条件查询",
            style = MaterialTheme.typography.h6,
            fontWeight = FontWeight.Bold
        )

        Spacer(modifier = Modifier.height(8.dp))

        Text(
            text = "使用 rememberMediaQuery 进行复杂条件组合",
            style = MaterialTheme.typography.body1,
            color = Color.Gray
        )

        Spacer(modifier = Modifier.height(16.dp))

        // 宽度查询
        val widthQuery = rememberMediaQuery("(width >= 600vp)")

        Card(
            modifier = Modifier.fillMaxWidth(),
            backgroundColor =
                if (widthQuery.matches.value)
                    MaterialTheme.colors.primaryVariant
                else
                    MaterialTheme.colors.surface

        ) {
            Column(
                modifier = Modifier.padding(16.dp)
            ) {
                Text(
                    text = "宽度查询",
                    fontSize = 18.sp,
                    fontWeight = FontWeight.Bold
                )

                Spacer(modifier = Modifier.height(8.dp))

                Text(
                    text = "条件: (width >= 600vp)",
                    fontSize = 12.sp,
                    fontFamily = androidx.compose.ui.text.font.FontFamily.Monospace,
                    color = Color.Gray
                )

                Spacer(modifier = Modifier.height(8.dp))

                Text(
                    text = "匹配状态: ${if (widthQuery.matches.value) "匹配" else "不匹配"}",
                    fontSize = 16.sp,
                    fontWeight = FontWeight.Bold,
                    color = if (widthQuery.matches.value)
                        MaterialTheme.colors.primary
                    else
                        Color.Gray
                )
            }
        }

        Spacer(modifier = Modifier.height(12.dp))

        // 横屏平板查询
        val tabletLandscape = rememberMediaQuery(
            "(device-type: tablet) and (orientation: landscape)"
        )

        Card(
            modifier = Modifier.fillMaxWidth(),
            backgroundColor =
                if (tabletLandscape.matches.value)
                    MaterialTheme.colors.secondary
                else
                    MaterialTheme.colors.surface

        ) {
            Column(
                modifier = Modifier.padding(16.dp)
            ) {
                Text(
                    text = "组合条件 - 横屏平板",
                    fontSize = 18.sp,
                    fontWeight = FontWeight.Bold
                )

                Spacer(modifier = Modifier.height(8.dp))

                Text(
                    text = "条件: (device-type: tablet) and (orientation: landscape)",
                    fontSize = 12.sp,
                    fontFamily = androidx.compose.ui.text.font.FontFamily.Monospace,
                    color = Color.Gray
                )

                Spacer(modifier = Modifier.height(8.dp))

                Text(
                    text = "匹配状态: ${if (tabletLandscape.matches.value) "匹配" else "不匹配"}",
                    fontSize = 16.sp,
                    fontWeight = FontWeight.Bold,
                    color = if (tabletLandscape.matches.value)
                        MaterialTheme.colors.secondary
                    else
                        Color.Gray
                )
            }
        }

        Spacer(modifier = Modifier.height(12.dp))

        // 大屏设备查询 (平板或TV)
        val largeScreen = rememberMediaQuery(
            "(device-type: tablet), (device-type: tv)"
        )

        Card(
            modifier = Modifier.fillMaxWidth(),
            backgroundColor =
                if (largeScreen.matches.value)
                    MaterialTheme.colors.primaryVariant
                else
                    MaterialTheme.colors.surface

        ) {
            Column(
                modifier = Modifier.padding(16.dp)
            ) {
                Text(
                    text = "或逻辑 - 大屏设备",
                    fontSize = 18.sp,
                    fontWeight = FontWeight.Bold
                )

                Spacer(modifier = Modifier.height(8.dp))

                Text(
                    text = "条件: (device-type: tablet), (device-type: tv)",
                    fontSize = 12.sp,
                    fontFamily = androidx.compose.ui.text.font.FontFamily.Monospace,
                    color = Color.Gray
                )

                Spacer(modifier = Modifier.height(8.dp))

                Text(
                    text = "匹配状态: ${if (largeScreen.matches.value) "匹配" else "不匹配"}",
                    fontSize = 16.sp,
                    fontWeight = FontWeight.Bold,
                    color = if (largeScreen.matches.value)
                        MaterialTheme.colors.primaryVariant
                    else
                        Color.Gray
                )
            }
        }

        Spacer(modifier = Modifier.height(12.dp))

        // 深色模式 + 横屏查询
        val darkLandscape = rememberMediaQuery(
            "(dark-mode: true) and (orientation: landscape)"
        )

        Card(
            modifier = Modifier.fillMaxWidth(),
            backgroundColor =
                if (darkLandscape.matches.value)
                    MaterialTheme.colors.primaryVariant
                else
                    MaterialTheme.colors.surface

        ) {
            Column(
                modifier = Modifier.padding(16.dp)
            ) {
                Text(
                    text = "深色横屏模式",
                    fontSize = 18.sp,
                    fontWeight = FontWeight.Bold
                )

                Spacer(modifier = Modifier.height(8.dp))

                Text(
                    text = "条件: (dark-mode: true) and (orientation: landscape)",
                    fontSize = 12.sp,
                    fontFamily = androidx.compose.ui.text.font.FontFamily.Monospace,
                    color = Color.Gray
                )

                Spacer(modifier = Modifier.height(8.dp))

                Text(
                    text = "匹配状态: ${if (darkLandscape.matches.value) "匹配" else "不匹配"}",
                    fontSize = 16.sp,
                    fontWeight = FontWeight.Bold,
                    color = if (darkLandscape.matches.value)
                        MaterialTheme.colors.primary
                    else
                        Color.Gray
                )
            }
        }
    }
}

/**
 * 示例 4: 动态响应演示
 * 展示媒体查询变化时的动态响应
 */
@Composable
private fun DynamicResponseDemo() {
    val isLandscape = rememberIsLandscape()
    val isDarkMode = rememberIsDarkMode()

    // 记录变化日志
    var changeLog by remember { mutableStateOf(listOf<String>()) }
    var logCounter by remember { mutableStateOf(0) }

    // 监听横屏变化
    val landscapeListener = rememberMediaQuery("(orientation: landscape)") { matches ->
        logCounter++
        val status = if (matches) "进入横屏" else "进入竖屏"
        changeLog = (changeLog + "[#$logCounter] $status").takeLast(8)
    }

    // 监听深色模式变化
    val darkModeListener = rememberMediaQuery("(dark-mode: true)") { matches ->
        logCounter++
        val status = if (matches) "进入深色模式" else "进入浅色模式"
        changeLog = (changeLog + "[#$logCounter] $status").takeLast(8)
    }

    // 动画效果
    val boxSize by animateDpAsState(
        targetValue = if (isLandscape.value) 120.dp else 80.dp
    )

    val boxColor by animateColorAsState(
        targetValue = if (isDarkMode.value)
            MaterialTheme.colors.primary
        else
            MaterialTheme.colors.error
    )

    Column(
        modifier = Modifier
            .fillMaxSize()
            .verticalScroll(rememberScrollState())
    ) {
        Text(
            text = "动态响应演示",
            style = MaterialTheme.typography.h6,
            fontWeight = FontWeight.Bold
        )

        Spacer(modifier = Modifier.height(8.dp))

        Text(
            text = "媒体查询变化时自动触发 UI 更新和动画",
            style = MaterialTheme.typography.body1,
            color = Color.Gray
        )

        Spacer(modifier = Modifier.height(16.dp))

        // 动画演示区域
        Card(
            modifier = Modifier.fillMaxWidth(),
            backgroundColor =
                MaterialTheme.colors.primaryVariant

        ) {
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(16.dp),
                horizontalAlignment = Alignment.CenterHorizontally
            ) {
                Text(
                    text = "响应式动画",
                    fontSize = 18.sp,
                    fontWeight = FontWeight.Bold,
                    color = MaterialTheme.colors.onPrimary
                )

                Spacer(modifier = Modifier.height(16.dp))

                // 响应式方块
                Box(
                    modifier = Modifier
                        .size(boxSize)
                        .background(boxColor, RoundedCornerShape(12.dp)),
                    contentAlignment = Alignment.Center
                ) {
                    Text(
                        text = "${boxSize.value.toInt()}dp",
                        color = Color.White,
                        fontWeight = FontWeight.Bold
                    )
                }

                Spacer(modifier = Modifier.height(16.dp))

                Text(
                    text = "方块大小随屏幕方向变化\n颜色随主题模式变化",
                    fontSize = 14.sp,
                    textAlign = TextAlign.Center,
                    color = MaterialTheme.colors.onPrimary.copy(alpha = 0.7f)
                )
            }
        }

        Spacer(modifier = Modifier.height(16.dp))

        // 自适应布局演示
        Card(
            modifier = Modifier.fillMaxWidth(),
            backgroundColor =
                MaterialTheme.colors.secondary

        ) {
            Column(
                modifier = Modifier.padding(16.dp)
            ) {
                Text(
                    text = "自适应布局",
                    fontSize = 18.sp,
                    fontWeight = FontWeight.Bold,
                    color = MaterialTheme.colors.onSecondary
                )

                Spacer(modifier = Modifier.height(16.dp))

                if (isLandscape.value) {
                    // 横屏布局
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.spacedBy(12.dp)
                    ) {
                        ContentBox(
                            modifier = Modifier.weight(1f),
                            title = "内容 A",
                            color = MaterialTheme.colors.primary.copy(alpha = 0.3f)
                        )
                        ContentBox(
                            modifier = Modifier.weight(1f),
                            title = "内容 B",
                            color = MaterialTheme.colors.secondary.copy(alpha = 0.3f)
                        )
                        ContentBox(
                            modifier = Modifier.weight(1f),
                            title = "内容 C",
                            color = MaterialTheme.colors.primaryVariant.copy(alpha = 0.3f)
                        )
                    }
                } else {
                    // 竖屏布局
                    Column(
                        verticalArrangement = Arrangement.spacedBy(12.dp)
                    ) {
                        ContentBox(
                            modifier = Modifier.fillMaxWidth(),
                            title = "内容 A",
                            color = MaterialTheme.colors.primary.copy(alpha = 0.3f)
                        )
                        ContentBox(
                            modifier = Modifier.fillMaxWidth(),
                            title = "内容 B",
                            color = MaterialTheme.colors.secondary.copy(alpha = 0.3f)
                        )
                        ContentBox(
                            modifier = Modifier.fillMaxWidth(),
                            title = "内容 C",
                            color = MaterialTheme.colors.primaryVariant.copy(alpha = 0.3f)
                        )
                    }
                }
            }
        }

        Spacer(modifier = Modifier.height(16.dp))

        // 变化日志
        Card(
            modifier = Modifier.fillMaxWidth(),
            backgroundColor =
                MaterialTheme.colors.surface

        ) {
            Column(
                modifier = Modifier.padding(16.dp)
            ) {
                Text(
                    text = "变化日志",
                    fontSize = 16.sp,
                    fontWeight = FontWeight.Bold
                )

                Spacer(modifier = Modifier.height(8.dp))

                if (changeLog.isEmpty()) {
                    Text(
                        text = "旋转设备或切换主题查看变化...",
                        fontSize = 12.sp,
                        color = Color.Gray
                    )
                } else {
                    changeLog.forEach { message ->
                        Text(
                            text = message,
                            fontSize = 12.sp,
                            modifier = Modifier.padding(vertical = 2.dp),
                            color = MaterialTheme.colors.primary
                        )
                    }
                }
            }
        }
    }
}

@Composable
private fun ContentBox(
    modifier: Modifier = Modifier,
    title: String,
    color: Color
) {
    Box(
        modifier = modifier
            .height(60.dp)
            .background(color, RoundedCornerShape(8.dp)),
        contentAlignment = Alignment.Center
    ) {
        Text(
            text = title,
            fontWeight = FontWeight.Bold
        )
    }
}

/**
 * 示例 5: 查询信息面板
 * 展示所有媒体查询相关信息
 */
@Composable
private fun QueryInfoDemo() {
    val isLandscape = rememberIsLandscape()
    val isDarkMode = rememberIsDarkMode()
    val deviceType = rememberDeviceType()

    // 创建媒体查询管理器
    val mediaQuery = createMediaQuery()
    val listenerCount = remember(mediaQuery) { mediaQuery.getListenerCount() }

    Column(
        modifier = Modifier
            .fillMaxSize()
            .verticalScroll(rememberScrollState())
    ) {
        Text(
            text = "媒体查询信息",
            style = MaterialTheme.typography.h6,
            fontWeight = FontWeight.Bold
        )

        Spacer(modifier = Modifier.height(16.dp))

        // 当前状态
        Card(
            modifier = Modifier.fillMaxWidth(),
            backgroundColor =
                MaterialTheme.colors.primaryVariant

        ) {
            Column(
                modifier = Modifier.padding(16.dp)
            ) {
                Text(
                    text = "当前媒体状态",
                    fontSize = 18.sp,
                    fontWeight = FontWeight.Bold,
                    color = MaterialTheme.colors.onPrimary
                )

                Spacer(modifier = Modifier.height(12.dp))

                InfoRow(
                    label = "屏幕方向",
                    value = if (isLandscape.value) "landscape" else "portrait"
                )

                Divider(
                    modifier = Modifier.padding(vertical = 8.dp),
                    color = MaterialTheme.colors.onPrimary.copy(alpha = 0.2f)
                )

                InfoRow(
                    label = "主题模式",
                    value = if (isDarkMode.value) "dark" else "light"
                )

                Divider(
                    modifier = Modifier.padding(vertical = 8.dp),
                    color = MaterialTheme.colors.onPrimary.copy(alpha = 0.2f)
                )

                InfoRow(
                    label = "设备类型",
                    value = deviceType.value.value
                )
            }
        }

        Spacer(modifier = Modifier.height(16.dp))

        // 支持的媒体特征
        Card(
            modifier = Modifier.fillMaxWidth(),
            backgroundColor =
                MaterialTheme.colors.secondary

        ) {
            Column(
                modifier = Modifier.padding(16.dp)
            ) {
                Text(
                    text = "支持的媒体特征",
                    fontSize = 18.sp,
                    fontWeight = FontWeight.Bold,
                    color = MaterialTheme.colors.onSecondary
                )

                Spacer(modifier = Modifier.height(12.dp))

                FeatureItem("width / height", "页面宽度/高度 (vp/px)")
                FeatureItem("orientation", "屏幕方向 (portrait/landscape)")
                FeatureItem("device-type", "设备类型 (phone/tablet/tv/...)")
                FeatureItem("dark-mode", "深色模式 (true/false)")
                FeatureItem("resolution", "分辨率 (dpi/dppx)")
                FeatureItem("device-width/height", "设备宽度/高度")
            }
        }

        Spacer(modifier = Modifier.height(16.dp))

        // 逻辑操作符
        Card(
            modifier = Modifier.fillMaxWidth(),
            backgroundColor =
                MaterialTheme.colors.primaryVariant

        ) {
            Column(
                modifier = Modifier.padding(16.dp)
            ) {
                Text(
                    text = "逻辑操作符",
                    fontSize = 18.sp,
                    fontWeight = FontWeight.Bold,
                    color = MaterialTheme.colors.onPrimary
                )

                Spacer(modifier = Modifier.height(12.dp))

                OperatorItem("and", "所有条件均满足")
                OperatorItem("or", "任一条件满足")
                OperatorItem("not", "条件取反")
                OperatorItem(">=, <=, >, <", "范围操作符")
            }
        }

        Spacer(modifier = Modifier.height(16.dp))

        // API 使用说明
        Card(
            modifier = Modifier.fillMaxWidth(),
            backgroundColor =
                MaterialTheme.colors.surface

        ) {
            Column(
                modifier = Modifier.padding(16.dp)
            ) {
                Text(
                    text = "主要 API",
                    fontSize = 18.sp,
                    fontWeight = FontWeight.Bold
                )

                Spacer(modifier = Modifier.height(12.dp))

                ApiItem(
                    api = "rememberMediaQuery(condition)",
                    desc = "创建媒体查询监听器"
                )
                ApiItem(
                    api = "rememberIsLandscape()",
                    desc = "查询是否横屏"
                )
                ApiItem(
                    api = "rememberIsDarkMode()",
                    desc = "查询是否深色模式"
                )
                ApiItem(
                    api = "rememberDeviceType()",
                    desc = "查询设备类型"
                )
                ApiItem(
                    api = "ProvideMediaQueryLocals { }",
                    desc = "提供全局媒体查询状态"
                )
            }
        }
    }
}

@Composable
private fun InfoRow(label: String, value: String) {
    Row(
        modifier = Modifier.fillMaxWidth(),
        horizontalArrangement = Arrangement.SpaceBetween,
        verticalAlignment = Alignment.CenterVertically
    ) {
        Text(
            text = label,
            fontSize = 14.sp,
            color = MaterialTheme.colors.onPrimary.copy(alpha = 0.7f)
        )
        Text(
            text = value.uppercase(),
            fontSize = 16.sp,
            fontWeight = FontWeight.Bold,
            color = MaterialTheme.colors.primary
        )
    }
}

@Composable
private fun FeatureItem(name: String, description: String) {
    Column(
        modifier = Modifier.padding(vertical = 4.dp)
    ) {
        Text(
            text = name,
            fontSize = 14.sp,
            fontWeight = FontWeight.Bold,
            fontFamily = androidx.compose.ui.text.font.FontFamily.Monospace,
            color = MaterialTheme.colors.onSecondary
        )
        Text(
            text = description,
            fontSize = 12.sp,
            color = Color.Gray
        )
    }
}

@Composable
private fun OperatorItem(operator: String, description: String) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .padding(vertical = 4.dp),
        horizontalArrangement = Arrangement.SpaceBetween
    ) {
        Text(
            text = operator,
            fontSize = 14.sp,
            fontWeight = FontWeight.Bold,
            fontFamily = androidx.compose.ui.text.font.FontFamily.Monospace,
            color = MaterialTheme.colors.onPrimary
        )
        Text(
            text = description,
            fontSize = 12.sp,
            color = Color.Gray
        )
    }
}

@Composable
private fun ApiItem(api: String, desc: String) {
    Column(
        modifier = Modifier.padding(vertical = 4.dp)
    ) {
        Text(
            text = api,
            fontSize = 12.sp,
            fontFamily = androidx.compose.ui.text.font.FontFamily.Monospace,
            color = MaterialTheme.colors.primary
        )
        Text(
            text = desc,
            fontSize = 12.sp,
            color = Color.Gray
        )
    }
}

// 辅助函数
private fun getDeviceTypeDisplayName(type: DeviceType): String {
    return when (type) {
        DeviceType.PHONE -> "手机"
        DeviceType.TABLET -> "平板"
        DeviceType.TV -> "电视"
        DeviceType.WEARABLE -> "穿戴设备"
        DeviceType.CAR -> "车载设备"
        DeviceType.TWO_IN_ONE -> "二合一设备"
        DeviceType.DEFAULT -> "默认设备"
    }
}

private fun getDeviceTypeColor(type: DeviceType): Color {
    return when (type) {
        DeviceType.PHONE -> Color(0xFF4CAF50)
        DeviceType.TABLET -> Color(0xFF2196F3)
        DeviceType.TV -> Color(0xFF9C27B0)
        DeviceType.WEARABLE -> Color(0xFFFF9800)
        DeviceType.CAR -> Color(0xFF795548)
        DeviceType.TWO_IN_ONE -> Color(0xFF607D8B)
        DeviceType.DEFAULT -> Color.Gray
    }
}

/**
 * 示例 6: 单位转换演示
 * 展示不同单位(vp/px/dp/pt)的媒体查询
 */
@Composable
private fun UnitConversionDemo() {
    // 测试不同单位的宽度查询
    val width600 = rememberMediaQuery("(width >= 600)")        // 无单位,默认dp
    val width600vp = rememberMediaQuery("(width >= 600vp)")
    val width1800px = rememberMediaQuery("(width >= 1800px)")  // 假设 density=3, 1800px = 600dp
    val width600dp = rememberMediaQuery("(width >= 600dp)")
    val width600pt = rememberMediaQuery("(width >= 600pt)")

    // 测试分辨率查询
    val resolution2dppx = rememberMediaQuery("(resolution >= 2dppx)")  // 2 * 96 = 192dpi
    val resolution320dpi =
        rememberMediaQuery("(resolution >= 2.6)")   // 媒体查询的1dppx = 96dpi，媒体查询（mediaquery）中定义的 dpi 标准 与 系统属性（display）中返回的 densityDPI 计算基准不同
    val resolution127dpcm = rememberMediaQuery("(resolution >= 76dpcm)")  // 76 * 2.54 ≈ 193.04dpi

    Column(
        modifier = Modifier
            .fillMaxSize()
            .verticalScroll(rememberScrollState())
    ) {
        Text(
            text = "单位转换演示",
            style = MaterialTheme.typography.h6,
            fontWeight = FontWeight.Bold
        )

        Spacer(modifier = Modifier.height(8.dp))

        Text(
            text = "展示不同单位系统的媒体查询效果",
            style = MaterialTheme.typography.body1,
            color = Color.Gray
        )

        Spacer(modifier = Modifier.height(16.dp))

        // 长度单位转换
        Card(
            modifier = Modifier.fillMaxWidth(),
            backgroundColor = MaterialTheme.colors.primaryVariant
        ) {
            Column(
                modifier = Modifier.padding(16.dp)
            ) {
                Text(
                    text = "长度单位查询",
                    fontSize = 18.sp,
                    fontWeight = FontWeight.Bold,
                    color = MaterialTheme.colors.onPrimary
                )

                Spacer(modifier = Modifier.height(12.dp))

                UnitQueryRow(
                    unit = "600",
                    description = "无单位 (默认为 DP)",
                    matches = width600.matches.value
                )

                Spacer(modifier = Modifier.height(8.dp))

                UnitQueryRow(
                    unit = "600vp",
                    description = "Virtual Pixel (HarmonyOS)",
                    matches = width600vp.matches.value
                )

                Spacer(modifier = Modifier.height(8.dp))

                UnitQueryRow(
                    unit = "1800px",
                    description = "Physical Pixel (density × dp)",
                    matches = width1800px.matches.value
                )

                Spacer(modifier = Modifier.height(8.dp))

                UnitQueryRow(
                    unit = "600dp",
                    description = "Density-independent Pixel (Android)",
                    matches = width600dp.matches.value
                )

                Spacer(modifier = Modifier.height(8.dp))

                UnitQueryRow(
                    unit = "600pt",
                    description = "Point (iOS, 1pt = 1dp)",
                    matches = width600pt.matches.value
                )
            }
        }

        Spacer(modifier = Modifier.height(16.dp))

        // 分辨率单位转换
        Card(
            modifier = Modifier.fillMaxWidth(),
            backgroundColor = MaterialTheme.colors.secondary
        ) {
            Column(
                modifier = Modifier.padding(16.dp)
            ) {
                Text(
                    text = "分辨率单位查询",
                    fontSize = 18.sp,
                    fontWeight = FontWeight.Bold,
                    color = MaterialTheme.colors.onSecondary
                )

                Spacer(modifier = Modifier.height(12.dp))

                UnitQueryRow(
                    unit = "2dppx",
                    description = "Dots Per Pixel (2 * 96 = 192dpi)",
                    matches = resolution2dppx.matches.value
                )

                Spacer(modifier = Modifier.height(8.dp))

                UnitQueryRow(
                    unit = "2.6",
                    description = "默认值为dppx，媒体查询（mediaquery）中定义的 dpi 标准 与 系统属性（display）中返回的 densityDPI 计算基准不同",
                    matches = resolution320dpi.matches.value
                )

                Spacer(modifier = Modifier.height(8.dp))

                UnitQueryRow(
                    unit = "60dpcm",
                    description = "Dots Per Centimeter (76 * 2.54 ≈ 193.04dpi)",
                    matches = resolution127dpcm.matches.value
                )
            }
        }

        Spacer(modifier = Modifier.height(16.dp))

        // 单位转换说明
        Card(
            modifier = Modifier.fillMaxWidth(),
            backgroundColor = MaterialTheme.colors.surface
        ) {
            Column(
                modifier = Modifier.padding(16.dp)
            ) {
                Text(
                    text = "单位转换规则",
                    fontSize = 16.sp,
                    fontWeight = FontWeight.Bold
                )

                Spacer(modifier = Modifier.height(8.dp))

                Text(
                    text = "长度单位:\n" +
                            "• 无单位 → DP (默认单位)\n" +
                            "• VP/DP/PT → DP (直接使用)\n" +
                            "• PX → DP (PX / density)\n\n" +
                            "分辨率单位:\n" +
                            "• 无单位 → DPPX (默认单位)\n" +
                            "• DPI → DPI (标准单位)\n" +
                            "• DPPX → DPI (DPPX × 96)\n" +
                            "• DPCM → DPI (DPCM × 2.54)\n\n" +
                            "示例:\n" +
                            "• (width >= 600) ≡ (width >= 600dp)\n" +
                            "• (resolution >= 2) ≡ (resolution >= 2dpi)\n" +
                            "注意:\n" +
                            "媒体查询（mediaquery）中定义的 dpi 标准 与 系统属性（display）中返回的 densityDPI 计算基准不同，所以直接使用屏幕倍率（dppx）进行查询，这通常比具体 dpi 更通用。",
                    fontSize = 12.sp,
                    color = Color.Gray,
                    lineHeight = 18.sp
                )
            }
        }
    }
}

@Composable
private fun UnitQueryRow(
    unit: String,
    description: String,
    matches: Boolean
) {
    Row(
        modifier = Modifier.fillMaxWidth(),
        horizontalArrangement = Arrangement.SpaceBetween,
        verticalAlignment = Alignment.CenterVertically
    ) {
        Column(modifier = Modifier.weight(1f)) {
            Text(
                text = unit,
                fontSize = 14.sp,
                fontWeight = FontWeight.Bold,
                fontFamily = androidx.compose.ui.text.font.FontFamily.Monospace,
                color = MaterialTheme.colors.onPrimary
            )
            Text(
                text = description,
                fontSize = 10.sp,
                color = Color.Gray
            )
        }

        Surface(
            shape = RoundedCornerShape(6.dp),
            color = if (matches) Color(0xFF4CAF50) else Color.Gray
        ) {
            Text(
                text = if (matches) "✓ 匹配" else "✗ 不匹配",
                modifier = Modifier.padding(horizontal = 8.dp, vertical = 4.dp),
                fontSize = 10.sp,
                color = Color.White,
                fontWeight = FontWeight.Bold
            )
        }
    }
}

/**
 * 示例 7: 嵌套条件演示
 * 展示复杂的逻辑嵌套
 */
@Composable
private fun NestedConditionDemo() {

    // 首先测试简单条件是否工作
    val simpleTabletQuery = rememberMediaQuery("(device-type: tablet)")
    val simplePortraitQuery = rememberMediaQuery("(orientation: portrait)")
    val simpleLandscapeQuery = rememberMediaQuery("(orientation: landscape)")
    val simpleDarkQuery = rememberMediaQuery("(dark-mode: true)")

    // 🧪 测试：只包含orientation的复杂查询（验证HarmonyOS是否支持复杂查询监听）
    val testSimpleAndQuery = rememberMediaQuery("(orientation: landscape) and (width >= 300vp)")
    val testSimpleOrQuery = rememberMediaQuery("(orientation: landscape), (orientation: portrait)")

    // 特定设备方向组合 - 使用逗号替代or
    val complexQuery2 = rememberMediaQuery(
        "(device-type: phone) and (orientation: landscape), (device-type: tablet) and (orientation: landscape)"
    )

    // 🔧 强制刷新：当基础查询变化时，强制所有依赖查询重组
    val refreshKey = remember {
        derivedStateOf {
            "${simpleTabletQuery.matches.value}_${simpleLandscapeQuery.matches.value}_${simplePortraitQuery.matches.value}"
        }
    }

    // 测试简单 and 组合（HarmonyOS原生支持）
    val simpleAndQuery = rememberMediaQuery("(device-type: phone) and (orientation: portrait)")

    // 测试简单 or 组合 - 使用逗号语法（HarmonyOS特殊规则）
    val simpleOrQuery = rememberMediaQuery("(device-type: tablet), (device-type: phone)")

    // 嵌套条件示例（使用逗号替代or）
    val complexQuery1 = rememberMediaQuery(
        "(width >= 600vp) and (height >= 800vp), (device-type: tablet)"
    )

    // NOT + 逗号组合
    val complexQuery3 = rememberMediaQuery(
        "not (width < 400vp), (device-type: wearable)"
    )

    val complexQuery4 = rememberMediaQuery(
        "(dark-mode: true) and (orientation: landscape), (width >= 800vp) and (height >= 1000vp)"
    )

    // 🔧 使用key包裹Column，强制在refreshKey变化时重组
    key(refreshKey.value) {
        Column(
            modifier = Modifier
                .fillMaxSize()
                .verticalScroll(rememberScrollState())
        ) {
            Text(
                text = "嵌套条件演示",
                style = MaterialTheme.typography.h6,
                fontWeight = FontWeight.Bold
            )

            Spacer(modifier = Modifier.height(8.dp))

            Text(
                text = "HarmonyOS特殊语法：\n• AND 连接多个条件\n• 逗号(,) 替代 OR 进行\"或\"连接\n• and 和 or 关键字不能混用",
                style = MaterialTheme.typography.body2,
                color = Color(0xFFFF9800),
                lineHeight = 18.sp,
                fontWeight = FontWeight.Bold
            )

            Spacer(modifier = Modifier.height(16.dp))

            // 🔍 添加实时监控指示器
            Card(
                modifier = Modifier.fillMaxWidth(),
                backgroundColor = Color(0xFF2196F3)
            ) {
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(12.dp),
                    horizontalArrangement = Arrangement.SpaceBetween,
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Column {
                        Text(
                            text = "🔄 状态更新监控",
                            fontSize = 14.sp,
                            fontWeight = FontWeight.Bold,
                            color = Color.White
                        )
                        Text(
                            text = "旋转屏幕时观察是否自动更新",
                            fontSize = 10.sp,
                            color = Color.White.copy(alpha = 0.7f)
                        )
                    }
                    Column(horizontalAlignment = Alignment.End) {
                        Text(
                            text = "当前: ${if (simpleLandscapeQuery.matches.value) "横屏" else "竖屏"}",
                            fontSize = 12.sp,
                            color = Color.White,
                            fontWeight = FontWeight.Bold
                        )
                        Text(
                            text = "测试AND: ${if (testSimpleAndQuery.matches.value) "✓" else "✗"}",
                            fontSize = 11.sp,
                            color = if (testSimpleAndQuery.matches.value) Color.Green else Color.Red,
                            fontWeight = FontWeight.Bold
                        )
                        Text(
                            text = "测试OR: ${if (testSimpleOrQuery.matches.value) "✓" else "✗"}",
                            fontSize = 11.sp,
                            color = if (testSimpleOrQuery.matches.value) Color.Green else Color.Red,
                            fontWeight = FontWeight.Bold
                        )
                        Text(
                            text = "复杂查询: ${if (complexQuery2.matches.value) "✓" else "✗"}",
                            fontSize = 12.sp,
                            color = if (complexQuery2.matches.value) Color.Green else Color.Red,
                            fontWeight = FontWeight.Bold
                        )
                    }
                }
            }

            Spacer(modifier = Modifier.height(16.dp))

            // 简单查询测试（验证基础功能）
            Card(
                modifier = Modifier.fillMaxWidth(),
                backgroundColor = MaterialTheme.colors.primaryVariant
            ) {
                Column(
                    modifier = Modifier.padding(16.dp)
                ) {
                    Text(
                        text = "简单查询测试（验证基础功能）",
                        fontSize = 16.sp,
                        fontWeight = FontWeight.Bold,
                        color = MaterialTheme.colors.onPrimary
                    )

                    Spacer(modifier = Modifier.height(12.dp))

                    SimpleTestRow("设备类型=平板", simpleTabletQuery.matches.value)
                    SimpleTestRow("方向=竖屏", simplePortraitQuery.matches.value)
                    SimpleTestRow("方向=横屏", simpleLandscapeQuery.matches.value)
                    SimpleTestRow("深色模式", simpleDarkQuery.matches.value)

                    Spacer(modifier = Modifier.height(8.dp))
                    Divider(color = MaterialTheme.colors.onPrimary.copy(alpha = 0.3f))
                    Spacer(modifier = Modifier.height(8.dp))

                    Text(
                        text = "组合查询测试",
                        fontSize = 14.sp,
                        fontWeight = FontWeight.Bold,
                        color = MaterialTheme.colors.onPrimary
                    )
                    Spacer(modifier = Modifier.height(8.dp))
                    SimpleTestRow("手机 AND 竖屏", simpleAndQuery.matches.value)
                    SimpleTestRow("平板 , 手机 (逗号=OR)", simpleOrQuery.matches.value)

                    Spacer(modifier = Modifier.height(8.dp))
                    Divider(color = MaterialTheme.colors.onPrimary.copy(alpha = 0.3f))
                    Spacer(modifier = Modifier.height(8.dp))
                }
            }

            Spacer(modifier = Modifier.height(16.dp))

            // 复杂查询 1
            ComplexQueryCard(
                title = "尺寸AND组合 , 平板",
                condition = "(width >= 600vp) and (height >= 800vp), (device-type: tablet)",
                explanation = "满足以下任一条件:\n1. 宽度≥600 且 高度≥800\n2. 设备类型为平板\n✅ 使用逗号替代or",
                matches = complexQuery1.matches.value
            )

            Spacer(modifier = Modifier.height(12.dp))

            // 复杂查询 2
            ComplexQueryCard(
                title = "特定设备方向组合",
                condition = "(device-type: phone) and (orientation: landscape), (device-type: tablet) and (orientation: landscape)",
                explanation = "满足以下任一条件:\n1. 手机 + 横屏\n2. 平板 + 横屏\n✅ 任何设备的横屏模式",
                matches = complexQuery2.matches.value
            )

            Spacer(modifier = Modifier.height(12.dp))

            // 复杂查询 3
            ComplexQueryCard(
                title = "NOT + 逗号组合",
                condition = "not (width < 400vp), (device-type: wearable)",
                explanation = "满足以下任一条件:\n1. 不满足宽度<400\n2. 穿戴设备\n✅ NOT和逗号混合",
                matches = complexQuery3.matches.value
            )

            Spacer(modifier = Modifier.height(12.dp))

            // 复杂查询 4
            ComplexQueryCard(
                title = "深色横屏 , 大屏",
                condition = "(dark-mode: true) and (orientation: landscape), (width >= 800vp) and (height >= 1000vp)",
                explanation = "满足以下任一条件:\n1. 深色模式 + 横屏\n2. 宽度≥800 且 高度≥1000\n✅ 逗号连接两个AND组合",
                matches = complexQuery4.matches.value
            )

            Spacer(modifier = Modifier.height(16.dp))

            // 嵌套语法说明
            Card(
                modifier = Modifier.fillMaxWidth(),
                backgroundColor = MaterialTheme.colors.surface
            ) {
                Column(
                    modifier = Modifier.padding(16.dp)
                ) {
                    Text(
                        text = "HarmonyOS语法规则",
                        fontSize = 16.sp,
                        fontWeight = FontWeight.Bold
                    )

                    Spacer(modifier = Modifier.height(8.dp))

                    Text(
                        text = "✅ 正确语法:\n" +
                                "• 使用 and 连接多个条件\n" +
                                "• 使用逗号(,)替代or进行\"或\"连接\n" +
                                "• and 和 逗号 可以混合使用\n\n" +
                                "❌ 错误语法:\n" +
                                "• and 和 or 关键字不能混用\n" +
                                "• 不能直接使用 or 关键字\n\n" +
                                "示例:\n" +
                                "• (A) and (B), (C) 表示 (A AND B) OR C\n" +
                                "• (A), (B) and (C) 表示 A OR (B AND C)",
                        fontSize = 12.sp,
                        color = Color.Gray,
                        lineHeight = 18.sp
                    )
                }
            }
        }
    }  // ✅ key块结束 - 强制在refreshKey变化时重组整个Column
}

@Composable
private fun SimpleTestRow(
    label: String,
    matches: Boolean
) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .padding(vertical = 4.dp),
        horizontalArrangement = Arrangement.SpaceBetween,
        verticalAlignment = Alignment.CenterVertically
    ) {
        Text(
            text = label,
            fontSize = 12.sp,
            color = MaterialTheme.colors.onPrimary
        )
        Surface(
            shape = RoundedCornerShape(4.dp),
            color = if (matches) Color(0xFF4CAF50) else Color(0xFFE57373)
        ) {
            Text(
                text = if (matches) "✓" else "✗",
                modifier = Modifier.padding(horizontal = 12.dp, vertical = 4.dp),
                fontSize = 12.sp,
                color = Color.White,
                fontWeight = FontWeight.Bold
            )
        }
    }
}

@Composable
private fun ComplexQueryCard(
    title: String,
    condition: String,
    explanation: String,
    matches: Boolean
) {
    Card(
        modifier = Modifier.fillMaxWidth(),
        backgroundColor = if (matches)
            MaterialTheme.colors.primaryVariant
        else
            MaterialTheme.colors.surface
    ) {
        Column(
            modifier = Modifier.padding(16.dp)
        ) {
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(
                    text = title,
                    fontSize = 16.sp,
                    fontWeight = FontWeight.Bold,
                    modifier = Modifier.weight(1f)
                )

                Surface(
                    shape = RoundedCornerShape(8.dp),
                    color = if (matches) Color(0xFF4CAF50) else Color.Gray
                ) {
                    Text(
                        text = if (matches) "✓ 匹配" else "✗ 不匹配",
                        modifier = Modifier.padding(horizontal = 10.dp, vertical = 4.dp),
                        fontSize = 12.sp,
                        color = Color.White,
                        fontWeight = FontWeight.Bold
                    )
                }
            }

            Spacer(modifier = Modifier.height(8.dp))

            Text(
                text = "条件:",
                fontSize = 10.sp,
                color = Color.Gray
            )

            Text(
                text = condition,
                fontSize = 10.sp,
                fontFamily = androidx.compose.ui.text.font.FontFamily.Monospace,
                color = MaterialTheme.colors.primary,
                lineHeight = 14.sp
            )

            Spacer(modifier = Modifier.height(8.dp))

            Text(
                text = "说明:",
                fontSize = 10.sp,
                color = Color.Gray
            )

            Text(
                text = explanation,
                fontSize = 11.sp,
                color = Color.DarkGray,
                lineHeight = 16.sp
            )
        }
    }
}

/**
 * 示例 8: 实战场景演示
 * 展示实际应用中的常见用例
 */
@Composable
private fun PracticalScenarioDemo() {
    val isLandscape = rememberIsLandscape()
    val isDarkMode = rememberIsDarkMode()
    val deviceType = rememberDeviceType()

    // 实战场景查询
    val isPhablet = rememberMediaQuery("(device-type: phone) and (width >= 600vp)")
    val isFoldableExpanded = rememberMediaQuery("(device-type: tablet) and (width >= 800vp)")
    val isCompactMode = rememberMediaQuery("(width < 600vp), (device-type: wearable)")

    Column(
        modifier = Modifier
            .fillMaxSize()
            .verticalScroll(rememberScrollState())
    ) {
        Text(
            text = "实战场景演示",
            style = MaterialTheme.typography.h6,
            fontWeight = FontWeight.Bold
        )

        Spacer(modifier = Modifier.height(8.dp))

        Text(
            text = "展示实际应用开发中的常见场景",
            style = MaterialTheme.typography.body1,
            color = Color.Gray
        )

        Spacer(modifier = Modifier.height(16.dp))

        // 场景 1: 响应式导航栏
        ScenarioCard(
            title = "响应式导航栏",
            description = "根据设备类型和屏幕宽度选择导航模式"
        ) {
            if (deviceType.value == DeviceType.PHONE && !isLandscape.value) {
                // 手机竖屏: 底部导航栏
                BottomNavigationDemo()
            } else {
                // 平板或手机横屏: 侧边栏
                SideNavigationDemo()
            }
        }

        Spacer(modifier = Modifier.height(12.dp))

        // 场景 2: 自适应列表
        ScenarioCard(
            title = "自适应列表/网格",
            description = "小屏显示列表,大屏显示网格"
        ) {
            if (isCompactMode.matches.value) {
                // 紧凑模式: 单列列表
                CompactListDemo()
            } else {
                // 正常模式: 多列网格
                val columns = when (deviceType.value) {
                    DeviceType.PHONE -> if (isLandscape.value) 3 else 2
                    DeviceType.TABLET -> if (isLandscape.value) 4 else 3
                    else -> 2
                }
                GridDemo(columns = columns)
            }
        }

        Spacer(modifier = Modifier.height(12.dp))

        // 场景 3: 主从布局
        ScenarioCard(
            title = "主从布局 (Master-Detail)",
            description = "大屏双栏,小屏单栏"
        ) {
            if (isFoldableExpanded.matches.value || (deviceType.value == DeviceType.TABLET && isLandscape.value)) {
                // 双栏布局
                MasterDetailLayoutDemo()
            } else {
                // 单栏布局
                SinglePaneLayoutDemo()
            }
        }

        Spacer(modifier = Modifier.height(12.dp))

        // 场景 4: 字体大小自适应
        ScenarioCard(
            title = "字体大小自适应",
            description = "根据设备类型调整字体大小"
        ) {
            val fontSize = when (deviceType.value) {
                DeviceType.WEARABLE -> 12.sp
                DeviceType.PHONE -> 14.sp
                DeviceType.TABLET -> 16.sp
                DeviceType.TV -> 20.sp
                else -> 14.sp
            }

            Text(
                text = "示例文本",
                fontSize = fontSize,
                fontWeight = FontWeight.Bold,
                modifier = Modifier.fillMaxWidth(),
                textAlign = TextAlign.Center
            )

            Spacer(modifier = Modifier.height(4.dp))

            Text(
                text = "当前字体大小: ${fontSize.value.toInt()}sp",
                fontSize = 10.sp,
                color = Color.Gray,
                modifier = Modifier.fillMaxWidth(),
                textAlign = TextAlign.Center
            )
        }

        Spacer(modifier = Modifier.height(12.dp))

        // 场景 5: 深色模式主题切换
        ScenarioCard(
            title = "深色模式主题",
            description = "根据系统主题自动调整颜色"
        ) {
            val backgroundColor = if (isDarkMode.value) Color(0xFF1E1E1E) else Color(0xFFF5F5F5)
            val textColor = if (isDarkMode.value) Color(0xFFE0E0E0) else Color(0xFF212121)

            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(80.dp)
                    .background(backgroundColor, RoundedCornerShape(8.dp)),
                contentAlignment = Alignment.Center
            ) {
                Column(
                    horizontalAlignment = Alignment.CenterHorizontally
                ) {
                    Text(
                        text = if (isDarkMode.value) "深色主题" else "浅色主题",
                        fontSize = 16.sp,
                        fontWeight = FontWeight.Bold,
                        color = textColor
                    )

                    Spacer(modifier = Modifier.height(4.dp))

                    Text(
                        text = "背景: ${backgroundColor.toHexString()}\n文字: ${textColor.toHexString()}",
                        fontSize = 10.sp,
                        color = textColor.copy(alpha = 0.7f),
                        textAlign = TextAlign.Center
                    )
                }
            }
        }

        Spacer(modifier = Modifier.height(16.dp))

        // 实战技巧
        Card(
            modifier = Modifier.fillMaxWidth(),
            backgroundColor = MaterialTheme.colors.surface
        ) {
            Column(
                modifier = Modifier.padding(16.dp)
            ) {
                Text(
                    text = "实战开发技巧",
                    fontSize = 16.sp,
                    fontWeight = FontWeight.Bold
                )

                Spacer(modifier = Modifier.height(8.dp))

                Text(
                    text = "1. 优先使用快捷查询函数(rememberIsLandscape等)\n" +
                            "2. 复杂条件使用rememberMediaQuery\n" +
                            "3. 在根组件使用ProvideMediaQueryLocals\n" +
                            "4. 利用onChange回调处理状态变化\n" +
                            "5. 组合使用多个查询实现复杂逻辑",
                    fontSize = 12.sp,
                    color = Color.Gray,
                    lineHeight = 18.sp
                )
            }
        }
    }
}

@Composable
private fun ScenarioCard(
    title: String,
    description: String,
    content: @Composable () -> Unit
) {
    Card(
        modifier = Modifier.fillMaxWidth(),
        backgroundColor = MaterialTheme.colors.surface
    ) {
        Column(
            modifier = Modifier.padding(16.dp)
        ) {
            Text(
                text = title,
                fontSize = 16.sp,
                fontWeight = FontWeight.Bold
            )

            Spacer(modifier = Modifier.height(4.dp))

            Text(
                text = description,
                fontSize = 12.sp,
                color = Color.Gray
            )

            Spacer(modifier = Modifier.height(12.dp))

            content()
        }
    }
}

@Composable
private fun BottomNavigationDemo() {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .height(56.dp)
            .background(MaterialTheme.colors.primary, RoundedCornerShape(8.dp)),
        horizontalArrangement = Arrangement.SpaceAround,
        verticalAlignment = Alignment.CenterVertically
    ) {
        repeat(4) { index ->
            Box(
                modifier = Modifier
                    .size(40.dp)
                    .background(Color.White.copy(alpha = 0.2f), RoundedCornerShape(8.dp)),
                contentAlignment = Alignment.Center
            ) {
                Text(
                    text = "${index + 1}",
                    color = Color.White,
                    fontWeight = FontWeight.Bold
                )
            }
        }
    }
}

@Composable
private fun SideNavigationDemo() {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .height(80.dp)
    ) {
        // 侧边栏
        Column(
            modifier = Modifier
                .width(100.dp)
                .fillMaxHeight()
                .background(MaterialTheme.colors.primary, RoundedCornerShape(8.dp))
                .padding(8.dp),
            verticalArrangement = Arrangement.SpaceAround,
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            repeat(3) { index ->
                Box(
                    modifier = Modifier
                        .size(32.dp)
                        .background(Color.White.copy(alpha = 0.2f), RoundedCornerShape(6.dp)),
                    contentAlignment = Alignment.Center
                ) {
                    Text(
                        text = "${index + 1}",
                        color = Color.White,
                        fontSize = 12.sp,
                        fontWeight = FontWeight.Bold
                    )
                }
            }
        }

        Spacer(modifier = Modifier.width(8.dp))

        // 内容区域
        Box(
            modifier = Modifier
                .weight(1f)
                .fillMaxHeight()
                .background(Color.LightGray.copy(alpha = 0.3f), RoundedCornerShape(8.dp)),
            contentAlignment = Alignment.Center
        ) {
            Text(
                text = "内容区域",
                fontSize = 12.sp,
                color = Color.Gray
            )
        }
    }
}

@Composable
private fun CompactListDemo() {
    Column(
        verticalArrangement = Arrangement.spacedBy(6.dp)
    ) {
        repeat(3) { index ->
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(40.dp)
                    .background(
                        MaterialTheme.colors.primary.copy(alpha = 0.2f),
                        RoundedCornerShape(6.dp)
                    ),
                contentAlignment = Alignment.Center
            ) {
                Text(
                    text = "列表项 ${index + 1}",
                    fontSize = 12.sp,
                    fontWeight = FontWeight.Bold
                )
            }
        }
    }
}

@Composable
private fun GridDemo(columns: Int) {
    Column(
        verticalArrangement = Arrangement.spacedBy(6.dp)
    ) {
        // 简化的网格演示
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.spacedBy(6.dp)
        ) {
            repeat(columns.coerceAtMost(4)) { index ->
                Box(
                    modifier = Modifier
                        .weight(1f)
                        .aspectRatio(1f)
                        .background(
                            MaterialTheme.colors.secondary.copy(alpha = 0.3f),
                            RoundedCornerShape(6.dp)
                        ),
                    contentAlignment = Alignment.Center
                ) {
                    Text(
                        text = "${index + 1}",
                        fontSize = 14.sp,
                        fontWeight = FontWeight.Bold
                    )
                }
            }
        }
    }
}

@Composable
private fun MasterDetailLayoutDemo() {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .height(100.dp),
        horizontalArrangement = Arrangement.spacedBy(8.dp)
    ) {
        // Master 列表
        Box(
            modifier = Modifier
                .weight(0.4f)
                .fillMaxHeight()
                .background(
                    MaterialTheme.colors.primary.copy(alpha = 0.2f),
                    RoundedCornerShape(8.dp)
                ),
            contentAlignment = Alignment.Center
        ) {
            Text(
                text = "列表",
                fontSize = 12.sp,
                fontWeight = FontWeight.Bold
            )
        }

        // Detail 详情
        Box(
            modifier = Modifier
                .weight(0.6f)
                .fillMaxHeight()
                .background(
                    MaterialTheme.colors.secondary.copy(alpha = 0.2f),
                    RoundedCornerShape(8.dp)
                ),
            contentAlignment = Alignment.Center
        ) {
            Text(
                text = "详情",
                fontSize = 12.sp,
                fontWeight = FontWeight.Bold
            )
        }
    }
}

@Composable
private fun SinglePaneLayoutDemo() {
    Box(
        modifier = Modifier
            .fillMaxWidth()
            .height(100.dp)
            .background(MaterialTheme.colors.primary.copy(alpha = 0.2f), RoundedCornerShape(8.dp)),
        contentAlignment = Alignment.Center
    ) {
        Text(
            text = "单栏内容",
            fontSize = 12.sp,
            fontWeight = FontWeight.Bold
        )
    }
}

// 辅助函数: Color 转 Hex 字符串
private fun Color.toHexString(): String {
    val r = (red * 255).toInt()
    val g = (green * 255).toInt()
    val b = (blue * 255).toInt()
    return "#${r.toString(16).padStart(2, '0')}${g.toString(16).padStart(2, '0')}${
        b.toString(16).padStart(2, '0')
    }".uppercase()
}
